package com.teachoa.web;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.teachoa.bean.Dict;
import com.teachoa.util.IDUtil;

public class DictController extends BaseController {

	public void index() {
		Page<Dict> page = Dict.dao.findDictByPage(1, null);
		setAttr("dictPage", page);
		renderJsp("dict.jsp");
	}
	
	public void tree() {
		renderJsp("tree.jsp");
	}
	
	public void json() {
		renderJson(JsonKit.toJson(Dict.dao.getDictTree()));
	}
	
	public void page() {
		Integer pageNo = getParaToInt("pageNo");
		String pid = getPara("pid");
		Page<Dict> page = Dict.dao.findDictByPage(pageNo, pid);
		setAttr("dictPage", page);
		renderJsp("dict_table.jsp");
	}
	
	public void load() {
		String id = getPara("id");
		String pid = getPara("pid");
		if(StringUtils.isNotBlank(id)) {
			Dict d = Dict.dao.findById(id);
			setAttr("dict", d);
			setAttr("pdict", Dict.dao.findById(d.getStr("pid")));
		}
		if(StringUtils.isNotBlank(pid))
			setAttr("pdict", Dict.dao.findById(pid));
		renderJsp("dict_add.jsp");
	}
	
	@Before(Tx.class)
	public void del() {
		try {
			Dict.dao.deleteById(getPara());
			renderJson(success("删除成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("删除失败！！"));
		}
	}
	
	@Before(Tx.class)
	public void save() {
		Dict dict = getModel(Dict.class);
		String id = dict.getStr("id");
		try {
			if(StringUtils.isBlank(id)) {
				dict.set("id", IDUtil.getId());
				dict.save();
			} else {
				dict.update();
			}
			renderJson(success("保存成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("保存失败！！"));
		}
	}

}
